<template>
  <div class="slide-enter-active">
    <nut-navbar @on-click-back="back" @on-click-title="title" title="个人信息"></nut-navbar>
    <nut-cell title="头像" is-link="true" @click="headleToUpHead"></nut-cell>
    <nut-cell title="昵称" desc="张三" is-link="true" @click="headleToUserName"></nut-cell>
    <nut-cell title="性别" desc="男" is-link="true" @click="headleToChooseGender"></nut-cell>
    <nut-cell title="生日" is-link="true" @click="headleToChooseDate"></nut-cell>
    <div>
      <nut-picker
          v-model:visible="showSex"
          :list-data="listData"
          @confirm="confirmSex"
      ></nut-picker>

      <nut-datepicker
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="confirmDate"
          v-model:visible="showDate"
          :is-show-chinese="false"
      ></nut-datepicker>
    </div>
    <input class="hide_file" ref="upLoadInput" type="file" id="input-control" name="file" @change="handleToUpload"
           accept="image/jpg, image/jpeg, image/png, image/gif"/>

    <nut-dialog :title="title" :close-on-click-overlay="false" v-model:visible="visible" :onCancel="reset"
                :onOk="getResult">
      <template v-slot:default>

        <vue-picture-cropper
            :presetMode="{mode:'round'}"
            :boxStyle="{width: '296px',height: '268px',backgroundColor: '#f8f8f8', margin: 'auto'}"
            :img="pic" :options="{viewMode: 1, dragMode: 'crop', aspectRatio: 1}"
            @ready="ready"
        />

      </template>

    </nut-dialog>


  </div>
</template>

<script>
import {reactive, ref, toRefs,} from "vue";
import {Toast} from '@nutui/nutui';
import VuePictureCropper, {cropper} from 'vue-picture-cropper'

export default {
  name: "userInfo",
  data() {
    return {
      visible: false,
      pic: ''
    }
  },
  setup() {
    const state = reactive({});
    const showSex = ref(false);
    const listData = ['男','女',];
    const title = '图片裁切';

    const headleToChooseGender = () => {
      showSex.value = true;
    }
    const confirmSex = (res) => {
      console.log(res)
    }

    const showDate = ref(false);
    const headleToChooseDate = () => {
      showDate.value = true;
    }
    const confirmDate = (res) => {
      console.log(res)
    }

    const headleToUpHead = () => {
      //调用input
      const file = document.getElementById('input-control')
      file.click();
    };

    return {
      state, ...toRefs(state), showSex, listData, showDate, title,
      headleToUpHead, headleToChooseGender, confirmSex, headleToChooseDate, confirmDate,
      minDate: new Date(1980, 0, 1),
      maxDate: new Date(),
    }
  },
  beforeRouteEnter(to, from, next) {//导航守卫
    const username = window.localStorage.getItem('name');

    if (username === null) {
      next('/mine/login');
    } else {
      next();
    }
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    handleToUpload(ev) {
      const file = ev.target.files[0];

      // 转换为base64传给裁切组件
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        // 更新裁切弹窗的图片源
        this.pic = reader.result
        // 显示裁切弹窗
        this.visible = true
        // 清空已选择的文件
        if (!this.$refs.upLoadInput.value) return
        this.$refs.upLoadInput.value = ''
      }
    },
    async getResult() {
      // const base64 = cropper.getDataURL()
      // 获取生成的blob文件信息
      // const blob = await cropper.getBlob()
      // 获取生成的file文件信息
      const file = await cropper.getFile({
        name: this.$store.state.user.name,
      })
      // console.log({base64, blob, file})

      //上传到服务器
      const param = new FormData();
      param.append('file', file, file.name);
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      };
      this.$axios.post('/api2/users/uploadUserHead', param, config).then((res) => {
        const status = res.data.status;
        const This = this;
        if (status === 0) {
          Toast.success('上传头像成功');
          This.$store.commit('user/USER_NAME', {
            name: This.$store.state.user.name,
            isAdmin: This.$store.state.user.isAdmin,
            userHead: res.data.data.userHead + '?' + Math.random()
          });
        } else {
          Toast.fail("上传头像失败");
        }
      });

      // 隐藏裁切弹窗
      this.visible = false
    },
    reset() {
      cropper.reset()
    },
    headleToUserName() {
      this.$router.push('/mine/updateUserName');

    }
  },
  components: {
    VuePictureCropper
  }
}
</script>

<style scoped>
.nut-navbar {
  padding: 0;
}

.hide_file {
  display: none;
}

</style>